import puza_stream_table as pst
import puza_row as pr
import puza_operator as po

class PuzaTableFilter:
    def __init__(self):
        self._filter_field = ''
        pass
    
    def _filter_by_field(self, r):
        if r[self._filter_field] != None:
            self._field_operator.Apply(r[self._filter_field])
    
    ## currently support first level fields
    def FilterByField(self, table, field_name, field_operator = po.PuzaOperator):
        self._filter_field = field_name
        self._field_operator = field_operator
        table.Restart()
        table.ReadLines(self._filter_by_field)
        return self._field_operator.Post()
    
class PuzaTableFilterSaveToTable:
    def __init__(self, output_filename = '', lformat = 0, block_number = 1):
        self._filter_field = ''
        self._lformat = lformat
        self._block_number = block_number
        self._internal_table = pst.PuzaStreamTable()
        self._internal_table.OutputFile(output_filename)
        pass
    
    def _filter_by_field(self, r):
        if r[self._filter_field] != None:
            result_row = self._field_operator.Apply(r[self._filter_field])
            if result_row != None:
                r = pr.PuzaRow()
                r[self._filter_field] = result_row
                self._internal_table.StreamOutRow(r, self._lformat, self._block_number)
    
    ## currently support first level fields
    def FilterByField(self, table, field_name, field_operator = po.PuzaOperator):
        self._filter_field = field_name
        self._field_operator = field_operator
        table.Restart()
        table.ReadLines(self._filter_by_field)
        ## post
        results = self._field_operator.Post()
        if results != None:
            r = pr.PuzaRow()   
            r['results'] = results
            self._internal_table.StreamOutRow(r, self._lformat, self._block_number)
        self._internal_table.StreamClose()
        return